package com.xinghou.platform.server.api.bussiness.impl;

import com.alibaba.fastjson.JSONObject;
import com.xinghou.platform.dao.main.common.DBSubjectLevelCached;
import com.xinghou.platform.entity.req.WeiXinShareReq;
import com.xinghou.platform.server.api.bussiness.WeixinShareService;
import com.xinghou.platform.util.HttpUtils;
import com.xinghou.platform.util.StringUtils;
import com.xinghou.platform.util.exception.DBExceptionEnums;
import com.xinghou.platform.util.exception.ServiceException;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by liufangyu on 2016/7/25.
 */
@Service("WeixinShareService")
public class WeixinShareServiceImpl extends DBSubjectLevelCached implements WeixinShareService {
    private static String APPID = "wxb6c14dc0f9762022";

    private static String APPSECRET = "15ba41db5bdd7eb252d80000fa8a821a";

    private static String TOKENURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    private static String TICKETURL = "http://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=";

    private static int CACHED_SHARE_DB_INDEX = 8;
    private static final String CACHE_SHARE_TOKEN="WEIXIN_SHARE_TOKEN"; //微信分享token
    private static final String CACHE_SHARE_TICKET="WEIXIN_SHARE_TICKET";  //微信分享ticket

    @Override
    public Map weixinShare(WeiXinShareReq weiXinShareReq){
        String token = getRedisClient().get(CACHE_SHARE_TOKEN, CACHED_SHARE_DB_INDEX);
        if(StringUtils.isBlank(token)||"null".equals(token)) {
           String result  = HttpUtils.get(TOKENURL+"&appid="+APPID+"&"+"secret="+APPSECRET);
            JSONObject json = JSONObject.parseObject(result);
            if(json.containsKey("access_token")){
                token = json.getString("access_token");
                getRedisClient().setex(CACHE_SHARE_TOKEN, 60 * 60, token, CACHED_SHARE_DB_INDEX);
            }else{
                throw new ServiceException(DBExceptionEnums.SERVER_INTEERFACE_ERROR);
            }
        }

        String jsapi_ticket = getRedisClient().get(CACHE_SHARE_TICKET, CACHED_SHARE_DB_INDEX);

        if(StringUtils.isBlank(jsapi_ticket)||"null".equals(jsapi_ticket)) {
            String result  = HttpUtils.get(TICKETURL+token);
            JSONObject json = JSONObject.parseObject(result);
            if(json.containsKey("ticket")){
                jsapi_ticket = json.getString("ticket");
                getRedisClient().setex(CACHE_SHARE_TICKET, 60 * 60, jsapi_ticket, CACHED_SHARE_DB_INDEX);
            }else{
                throw new ServiceException(DBExceptionEnums.SERVER_INTEERFACE_ERROR);
            }
        }




        // 注意 URL 一定要动态获取，不能 hardcode
        String url = weiXinShareReq.getUrl();
        Map<String, String> ret = sign(jsapi_ticket, url);
/*        for (Map.Entry entry : ret.entrySet()) {
            System.out.println(entry.getKey() + ", " + entry.getValue());
        }*/
        return  ret;
    }

    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
